package com.example.demo.thread.thread;

import java.util.Random;

/**
 * 线程启动与可见性
 * 父线程在启动子线程之前 对共享变量的更新对于子线程来说是可见的
 * @author: htc
 * @date: Created in 16:16 2019/1/7.
 */
public class ThreadStartVisibility {
    //线程间的共享变量
    static int data = 0;

    public static void main(String[] args) {
        Thread thread = new Thread(){
            @Override
            public void run() {
                //使当前线程休眠R秒(R为随机数)
                try {
                    Thread.sleep(new Random().nextInt(50));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                //读取并打印data的值
                System.out.println(data);
            }
        };

        //在子线程thread启动前更新变量data的值
        data = 1;
        thread.start();

        //使当前线程休眠R毫秒(R的值为随机数)
        try {
            Thread.sleep(new Random().nextInt(50));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //在子线程Thread启动后更新变量data的值
        data = 2;
    }
}
